package com.geek.novel.services

import android.content.res.Resources
import com.geek.novel.bo.AppContext
import com.geek.novel.entity.BookCrawler
import com.geek.novel.utils.GsonUtil
import com.vicpin.krealmextensions.query
import com.vicpin.krealmextensions.queryFirst
import com.vicpin.krealmextensions.save
import io.realm.Realm

class BookCrawlerRepository{
	
	private fun getResources(): Resources {
		return AppContext.getResources()
	}
	
	/**保存*/
	fun save(entity: BookCrawler){
		entity.save()
	}

	/**保存List*/
	fun saveAll(list: List<BookCrawler>){
		val jsonList = GsonUtil.toJsonTime(list)
		val realm = Realm.getDefaultInstance()
		//开启事务，然后批量保存
		realm.executeTransaction {
			it.createOrUpdateAllFromJson(BookCrawler::class.java, jsonList)
		}
	}

	fun findById(id: Long): BookCrawler?{
		return BookCrawler().queryFirst{equalTo("id", id)}
	}
	
	/**根据bookId获取数据*/
	fun findByBookId(bookId: String): List<BookCrawler> {
		return BookCrawler().query { equalTo("bookId", bookId) }
	}

	/**根据crawlSourceId和bookId获取数据*/
	fun findByCrawlSourceIdAndBookId(crawlSourceId: String, bookId: String): BookCrawler? {
		return BookCrawler().queryFirst { equalTo("bookId", bookId).and().equalTo("crawlSourceId", crawlSourceId) }
	}
	
}